<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>我的第一个 PWA</title>
  <!-- 引入 Manifest -->
  <link rel="manifest" href="manifest.json">
  <!-- 针对 iOS 的图标和启动画面设置 -->
  <link rel="apple-touch-icon" href="icon-192x192.png">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      padding: 20px;
    }
    button {
      padding: 10px 20px;
      font-size: 16px;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <h1>我的 PWA 应用</h1>
  <p id="status">正在检查网络状态...</p>
  <button onclick="checkOfflineMode()">测试离线模式</button>
  <button onclick="viewCaches()">查看缓存内容</button>
  <pre id="cache-output" style="text-align: left; white-space: pre-wrap; background: #f7f7f7; padding: 10px; border-radius: 6px; max-width: 800px; margin: 16px auto;"></pre>

  <script>
    // 注册 Service Worker
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', () => {
        navigator.serviceWorker.register('/sw.js')
          .then(registration => {
            console.log('Service Worker 注册成功:', registration.scope);
          })
          .catch(error => {
            console.log('Service Worker 注册失败:', error);
          });
      });
    }

    // 检查网络状态
    function updateNetworkStatus() {
      const statusElement = document.getElementById('status');
      if (navigator.onLine) {
        statusElement.textContent = '当前在线';
        statusElement.style.color = 'green';
      } else {
        statusElement.textContent = '当前离线（使用缓存数据）';
        statusElement.style.color = 'red';
      }
    }

    // 监听网络状态变化
    window.addEventListener('online', updateNetworkStatus);
    window.addEventListener('offline', updateNetworkStatus);
    updateNetworkStatus();

    // 测试离线模式
    function checkOfflineMode() {
      fetch('data.json')
        .then(response => response.json())
        .then(data => {
          alert('获取数据成功: ' + data.message);
        })
        .catch(error => {
          alert('获取数据失败（可能处于离线状态）: ' + error.message);
        });
    }

    // 查看 Cache Storage 中的缓存内容
    async function viewCaches() {
      const outputElement = document.getElementById('cache-output');
      if (!('caches' in window)) {
        outputElement.textContent = '当前浏览器不支持 Cache Storage';
        return;
      }

      try {
        const cacheNames = await caches.keys();
        if (!cacheNames.length) {
          outputElement.textContent = '没有找到任何缓存。';
          return;
        }

        const allResults = [];
        for (const name of cacheNames) {
          const cache = await caches.open(name);
          const requests = await cache.keys();
          const items = requests.map(req => {
            const url = req.url;
            // 尽量显示相对路径，便于阅读
            const relative = url.startsWith(location.origin) ? url.replace(location.origin, '') : url;
            return relative || '/';
          });
          allResults.push({ cacheName: name, items });
        }

        outputElement.textContent = JSON.stringify(allResults, null, 2);
      } catch (err) {
        outputElement.textContent = '读取缓存失败: ' + (err && err.message ? err.message : String(err));
      }
    }
  </script>
</body>
</html>
